<?php

/* UPDATING VALUES IN DATABASE */

echo"<p>Updating...";
$sql = "UPDATE $tableName SET ";
for ($i=0; $i< $fields; $i++) {
        if ($i!=0) {
                $sql = $sql . ", ";
        }
        $name = mysql_field_name($result, $i);
	/* Checking for empty input when the not_null flag is set */
        if (($plain[$i] == "") && (strpos(mysql_field_flags($result, $i), "not_null")!==false)) {
		$error_field = mysql_field_name($result, $i);
		$error_exists = true;
	} else if ($plain[$i] == "") {
		$sql = $sql . $name . "=NULL";
	} else {
		$sql = $sql . $name . "='" . $plain[$i] .  "'";
	}
}
$sql = $sql . " WHERE " . mysql_field_name($result, 0) . "='" . $plain[0] . "'";
//echo "<p>$sql</p>";

if (!$error_exists) {
	if (!mysql_query($sql)) {
		echo "<p>Error: (" . mysql_errno() . ") " .  mysql_error() . "...<strong>Unable to update data!</strong></p>\n";
		$error_exists = true;
		if (mysql_errno()==1452) {
			preg_match("/^([^`]*)`([^`]*)`.`([^`]*)`, CONSTRAINT `([^`]*)` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)\)$/", mysql_error(), $matches);
			$error_field=$matches[5];
		} else $error_field="";
	} else {
	        echo "...Done</p>\n";
	}
}

if ($error_exists) {
	echo "</p><p class=\"error-message\">Error: System is unable to update record! ";
	if ($error_field!="") {
		echo "Please review field \"" . $error_field . "\".</p>";
	} else echo "Please review and change inputted fields and try again.</p>";

	if ($_GET['input'] == 'plain') {
		$_POST['Submit'] = 'Plain Text Edit';
	} else {
		$_POST['Submit'] = 'Form Edit';
	}

}

?>
